package com.neusoft.yiyang.care.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neusoft.yiyang.care.mapper.CareRecordMapper;
import com.neusoft.yiyang.care.mapper.CareRecordModifyRequestMapper;
import com.neusoft.yiyang.care.service.CareRecordModifyRequestService;
import com.neusoft.yiyang.common.entity.care.CareRecord;
import com.neusoft.yiyang.common.entity.care.CareRecordModifyRequest;
import com.neusoft.yiyang.common.enums.ApprovalStatus;
import com.neusoft.yiyang.common.enums.ExecutionStatus;
import com.neusoft.yiyang.common.exception.BusinessException;
import com.neusoft.yiyang.common.utils.OssUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Service
public class CareRecordModifyRequestServiceImpl implements CareRecordModifyRequestService {

    @Autowired
    private CareRecordModifyRequestMapper modifyRequestMapper;

    @Autowired
    private CareRecordMapper careRecordMapper;

    @Autowired
    private OssUploadUtils ossUploadUtils;

    @Override
    public void submitModifyRequest(
            Integer applicantId,
            Integer originalRecordId,
            Integer careItemId,
            Integer caretakerId,
            Date careTime,
            Integer quantity,
            String feedback,
            String status,
            MultipartFile file
    ) {
        // 1. 校验必填参数
        if (applicantId == null) {
            throw new BusinessException(7001, "申请人ID不能为空");
        }
        if (originalRecordId == null) {
            throw new BusinessException(7002, "原记录ID不能为空");
        }

        // 2. 校验原记录是否存在
        CareRecord originalRecord = careRecordMapper.selectById(originalRecordId);
        if (originalRecord == null) {
            throw new BusinessException(7003, "原护理记录不存在");
        }

        // 3. 校验是否有未审批的申请
        if (hasPendingRequest(originalRecordId)) {
            throw new BusinessException(7004, "该记录已有未审批的修改申请");
        }

        // 4. 处理文件上传（如果有）
        String photoUrl = null;
        if (file != null && !file.isEmpty()) {
            String folder = "care-photos/modify-requests/" + LocalDate.now();
            photoUrl = ossUploadUtils.uploadFile(file, folder);
        }

        // 5. 创建修改申请对象并填充数据
        CareRecordModifyRequest request = new CareRecordModifyRequest();
        request.setApplicantId(applicantId);
        request.setOriginalRecordId(originalRecordId);
        request.setCareItemId(careItemId);
        request.setCaretakerId(caretakerId);
        request.setCareTime(careTime);
        request.setQuantity(quantity);
        request.setFeedback(feedback);

        // 将字符串状态转换为枚举（假设存在枚举转换逻辑）
        if (status != null) {
            try {
                request.setStatus(ExecutionStatus.valueOf(status));
            } catch (IllegalArgumentException e) {
                throw new BusinessException(7005, "无效的状态值");
            }
        }

        request.setPhotoUrl(photoUrl); // 设置照片URL
        request.setApplyTime(new Date());
        request.setApprovalStatus(ApprovalStatus.pending);

        // 6. 保存修改申请
        modifyRequestMapper.insert(request);
    }

    @Override
    @Transactional
    public void updateModifyRequest(
            Integer requestId,
            Integer applicantId,
            Integer originalRecordId,
            Integer careItemId,
            Integer caretakerId,
            Date careTime,
            Integer quantity,
            String feedback,
            String status,
            MultipartFile file) {

        // 1. 校验必填参数
        if (requestId == null) {
            throw new BusinessException(706, "申请ID不能为空");
        }
        if (applicantId == null) {
            throw new BusinessException(7007, "申请人ID不能为空");
        }
        if (originalRecordId == null) {
            throw new BusinessException(7008, "原记录ID不能为空");
        }

        // 2. 校验申请是否存在
        CareRecordModifyRequest request = modifyRequestMapper.selectById(requestId);
        if (request == null) {
            throw new BusinessException(7009, "修改申请不存在");
        }

        // 3. 校验申请人是否为申请的提交者
        if (!applicantId.equals(request.getApplicantId())) {
            throw new BusinessException(7010, "无权修改他人的申请");
        }

        // 4. 处理文件上传（如果有）
        String photoUrl = request.getPhotoUrl(); // 默认保留原照片
        if (file != null && !file.isEmpty()) {
            String folder = "care-photos/modify-requests/" + LocalDate.now();
            photoUrl = ossUploadUtils.uploadFile(file, folder);
        }

        // 5. 更新申请信息
        request.setCareItemId(careItemId);
        request.setCaretakerId(caretakerId);
        request.setCareTime(careTime);
        request.setQuantity(quantity);
        request.setFeedback(feedback);

        // 更新状态枚举
        if (status != null) {
            try {
                request.setStatus(ExecutionStatus.valueOf(status));
            } catch (IllegalArgumentException e) {
                throw new BusinessException(7011, "无效的状态值");
            }
        }

        // 更新照片URL（如果有新照片）
        if (file != null && !file.isEmpty()) {
            request.setPhotoUrl(photoUrl);
        }

        // 重置为待审核状态
        request.setApprovalStatus(ApprovalStatus.pending);
        request.setApplyTime(new Date()); // 更新申请时间
        request.setApproverId(null); // 清空审批人
        request.setApproveTime(null); // 清空审批时间
        request.setApprovalRemark(null); // 清空审批备注

        // 6. 保存更新
        modifyRequestMapper.updateById(request);
    }

    @Override
    @Transactional
    public void approveModifyRequest(Integer requestId, ApprovalStatus status, Integer approverId, String approvalRemark) {
        // 1. 校验审批人ID
        if (approverId == null) {
            throw new BusinessException(7012, "审批人ID不能为空");
        }

        // 2. 拒绝时校验备注是否存在
        if (ApprovalStatus.rejected.equals(status) && (approvalRemark == null || approvalRemark.trim().isEmpty())) {
            throw new BusinessException(7013, "拒绝申请必须填写备注说明原因");
        }

        // 3. 校验申请是否存在且未处理
        CareRecordModifyRequest request = modifyRequestMapper.selectById(requestId);
        if (request == null) {
            throw new BusinessException(7014, "修改申请不存在");
        }
        if (!ApprovalStatus.pending.equals(request.getApprovalStatus())) {
            throw new BusinessException(7015, "该申请已处理，无法重复操作");
        }

        // 4. 更新申请状态和审批人信息
        request.setApprovalStatus(status);
        request.setApproverId(approverId);
        request.setApproveTime(new Date());
        request.setApprovalRemark(approvalRemark);

        modifyRequestMapper.updateById(request);

        // 5. 审批通过时，更新原护理记录
        if (ApprovalStatus.approved.equals(status)) {
            CareRecord originalRecord = careRecordMapper.selectById(request.getOriginalRecordId());
            originalRecord.setCareItemId(request.getCareItemId());
            originalRecord.setCaretakerId(request.getCaretakerId());
            originalRecord.setCareTime(request.getCareTime());
            originalRecord.setQuantity(request.getQuantity());
            originalRecord.setFeedback(request.getFeedback());
            originalRecord.setStatus(request.getStatus());
            originalRecord.setPhotoUrl(request.getPhotoUrl());
            careRecordMapper.updateById(originalRecord);
        }
    }

    @Override
    public List<CareRecordModifyRequest> getAllRequests(
            Integer originalRecordId,
            String approvalStatus) {

        LambdaQueryWrapper<CareRecordModifyRequest> wrapper = new LambdaQueryWrapper<>();
        if (originalRecordId != null) {
            wrapper.eq(CareRecordModifyRequest::getOriginalRecordId, originalRecordId);
        }
        if (approvalStatus != null) {
            ApprovalStatus status = ApprovalStatus.valueOf(approvalStatus);
            wrapper.eq(CareRecordModifyRequest::getApprovalStatus, status);
        }
        // 按申请时间倒序
        wrapper.orderByDesc(CareRecordModifyRequest::getApplyTime);
        return modifyRequestMapper.selectList(wrapper); // 直接查询列表
    }

    @Override
    public boolean hasPendingRequest(Integer originalRecordId) {
        LambdaQueryWrapper<CareRecordModifyRequest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CareRecordModifyRequest::getOriginalRecordId, originalRecordId)
               .eq(CareRecordModifyRequest::getApprovalStatus, ApprovalStatus.pending);
        return modifyRequestMapper.selectCount(wrapper) > 0;
    }
}